﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.IO.Pipes;
using Landscape.Business;
using Landscape.Business.FNH;
using Landscape.Business.FNH.Activities;
using Landscape.Business.Entities;

namespace Landscape.WebApp
{
    public partial class TestPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (var nhSession = NHSessionManager.GetManager().GetSession())
                {
                    AdminActivities scts = new AdminActivities(nhSession);
                    this.DropDownList1.DataSource = scts.GetSystemAdminModules("INTERNAL");
                    this.DropDownList1.DataBind();

                    this.RadListBox1.DataSource = scts.GetAllDepartments();
                    this.RadListBox1.DataBind();
                }
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string module = this.DropDownList1.SelectedValue;

            if (module.Trim() != string.Empty)
            {
                using (var nhSession = NHSessionManager.GetManager().GetSession())
                {
                    AdminActivities scts = new AdminActivities(nhSession);
                    var sm = scts.GetSystemModuleByCode(Guid.Parse(module.Trim()));
                    RadListBox1.ClearChecked();

                    foreach (var item in sm.Departments)
                    {
                        if (RadListBox1.FindItemByValue(item.ID.ToString()) != null)
                            RadListBox1.FindItemByValue(item.ID.ToString()).Checked = true;
                    }

                }
            }
        }

        protected void RadButton1_Click(object sender, EventArgs e)
        {
            using (var nhSession = NHSessionManager.GetManager().GetSession())
            {
                using (var trans = nhSession.BeginTransaction())
                {
                    AdminActivities scts = new AdminActivities(nhSession);
                    var sm = scts.GetSystemModuleByCode(Guid.Parse(DropDownList1.SelectedValue));

                    while (sm.Departments.Count > 0)
                    {
                        sm.Departments.RemoveAt(0);
                    }

                    foreach (var item in RadListBox1.CheckedItems)
                    {
                        sm.Departments.Add(scts.GetDepartmentByID(Guid.Parse(item.Value)));
                    }

                    nhSession.SaveOrUpdate(sm);

                    trans.Commit();
                }
            }
        }
    }
}